﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using RuleCode.Common;
using System.IO;
using RuleCode.WebControls;
using System.Data;      

namespace ERPTemplate.Public
{
    public partial class UpdateFilter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AssemblyClass.MyAssembly = Assembly.Load("RuleCode");     

            bool typeRight = (Request["type"] == "edit" && !string.IsNullOrEmpty(Request["refid"])) || (Request["type"] == "new");

            if (RuleCode.Common.AssemblyClass.MyAssembly != null && !String.IsNullOrEmpty(Request["tablename"]) &&
                !String.IsNullOrEmpty(Request["id"]) && !String.IsNullOrEmpty(Request["queryname"]) && typeRight)
            {
            }
            else
            {
                Response.Clear();
                Response.Write("您没有权限访问该页面！");
                Response.End();
            }

            if (!IsPostBack)
            {
                InitPageData();
            }

        }

        #region 辅助方法

        /// <summary>
        /// 初始化页面的数据
        /// </summary>
        private void InitPageData()
        {

            try
            {
                string tableFullName = AssemblyClass.GetTypeFullName(Request["tablename"], typeof(RuleCode.Common.Table));
                if (!String.IsNullOrEmpty(tableFullName))
                {
                    TableNameLabel.Text = Request["tablename"];

                    RuleCode.Common.Table table = AssemblyClass.MyAssembly.CreateInstance(tableFullName) as RuleCode.Common.Table;
                    if (table.AllFields != null && table.AllFields.Count > 0)
                    {
                        DropDownList_FieldName.Items.Clear();
                        foreach (string fieldName in table.AllFields)
                        {
                            if(fieldName !="DATAAREAID")
                                DropDownList_FieldName.Items.Add(fieldName);
                        }
                        if (DropDownList_FieldName.Items.Count > 0)
                            DropDownList_FieldName.SelectedIndex = 0;
                    }
                    
                    //初始化 过滤操作
                    DropDownList_FilterAction.Items.Clear();
                    DropDownList_FilterAction.Items.Add("=");

                    string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
                    string queryXmlFileName = Path.Combine(queryXmlFilePath, Request["queryname"] + ".xml");
                    RuleQueryTable.CreateNewQueryXmlFile(queryXmlFileName);
                    if (Request["type"] == "edit")
                    {
                        InfoB.InnerText = "修改过滤条件";
                        if (File.Exists(queryXmlFileName))
                        {
                            DataSet dSet = new DataSet();
                            dSet.ReadXml(queryXmlFileName);
                            DataTable rangeDataTable = dSet.Tables[RuleQueryTable.RangeDataTableName ];
                            if (rangeDataTable != null)
                            {
                                DataRow[] dRows = rangeDataTable.Select("ID='" + Request["refid"] + "'");
                                if (dRows.Length > 0)
                                {
                                    string fieldName = dRows[0]["字段名"].ToString();
                                    string filterAction = dRows[0]["过滤操作"].ToString();
                                    string filterValue = dRows[0]["设置的值"].ToString();   
                                    string desc = dRows[0]["设置描述"].ToString();
                                    TextBox_FilterValue.Text = filterValue;



                                    DropDownList_FieldName.SelectedIndex = -1;
                                    bool hasFound = false;
                                    for (int i = 0; i < DropDownList_FieldName.Items.Count; i++)
                                    {
                                        if (DropDownList_FieldName.Items[i].Text == fieldName)
                                        {
                                            DropDownList_FieldName.Items[i].Selected = true;
                                            hasFound = true;
                                            break;
                                        }
                                    }
                                    if (!hasFound && DropDownList_FieldName.Items.Count > 0)
                                        DropDownList_FieldName.SelectedIndex = 0;

                                    InitFieldType();//根据字段类型初始化FilterAction和FilterValue

                                    hasFound = false;
                                    DropDownList_FilterAction.SelectedIndex = -1;
                                    for (int i = 0; i < DropDownList_FilterAction.Items.Count; i++)
                                    {
                                        if (DropDownList_FilterAction.Items[i].Text == filterAction)
                                        {
                                            hasFound = true;
                                            DropDownList_FilterAction.Items[i].Selected = true;
                                            break;
                                        }
                                    }
                                    if (!hasFound && DropDownList_FilterAction.Items.Count > 0)
                                        DropDownList_FilterAction.SelectedIndex = 0;

                                    if (DropDownList_FilterValue.Visible)
                                    {
                                        hasFound = false;
                                        DropDownList_FilterValue.SelectedIndex = -1;
                                        for (int i = 0; i < DropDownList_FilterValue.Items.Count; i++)
                                        {
                                            if (DropDownList_FilterValue.Items[i].Value == filterValue)
                                            {
                                                hasFound = true;
                                                DropDownList_FilterValue.Items[i].Selected = true;
                                                break;
                                            }
                                        }
                                        if (!hasFound && DropDownList_FilterValue.Items.Count >0)
                                            DropDownList_FilterValue.SelectedIndex = 0;
                                    }
                                    
                                }
                            }
                        }
                    }
                    else
                    {
                        InfoB.InnerText = "新建过滤条件";
                        InitFieldType();
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(this.Page, error.Message);
            }
        }


        /// <summary>
        /// 根据字段的类型获取 过滤操作的类型 以及 过滤条件的值（枚举）
        /// </summary>
        private void InitFieldType()
        {
            DropDownList_FilterAction.Items.Clear();
            DropDownList_FilterAction.Items.Add("=");
            DropDownList_FilterAction.Items.Add("!=");

            TextBox_FilterValue.Visible = true;
            DropDownList_FilterValue.Visible = false;

            string tableFullName = AssemblyClass.GetTypeFullName(Request["tablename"], typeof(RuleCode.Common.Table));
            System.Type tableType = AssemblyClass.MyAssembly.GetType(tableFullName);
            if (tableType != null)
            {
                PropertyInfo fieldInfo = tableType.GetProperty(DropDownList_FieldName.SelectedValue);
                if (fieldInfo != null)
                {
                    System.Type fieldType = fieldInfo.PropertyType ;
                    if (CaptionAttribute.Instance.NumeralTypes.Contains(fieldType.BaseType))
                    {
                        if (String.IsNullOrEmpty(TextBox_FilterValue.Attributes["BaseType"]))
                            TextBox_FilterValue.Attributes.Add("BaseType", fieldType.BaseType.Name);
                        else
                            TextBox_FilterValue.Attributes["BaseType"] = fieldType.BaseType.Name;
                 
                        DropDownList_FilterAction.Items.Add(">=");
                        DropDownList_FilterAction.Items.Add("<=");
                        DropDownList_FilterAction.Items.Add(">");
                        DropDownList_FilterAction.Items.Add("<");      
                    }
                    else if (CaptionAttribute.Instance.TStringTypes.Contains(fieldType.BaseType))
                    {
                        if (String.IsNullOrEmpty(TextBox_FilterValue.Attributes["BaseType"]))
                            TextBox_FilterValue.Attributes.Add("BaseType", fieldType.BaseType.Name);
                        else
                            TextBox_FilterValue.Attributes["BaseType"] = fieldType.BaseType.Name;

                        DropDownList_FilterAction.Items.Add("NOT LIKE");
                        DropDownList_FilterAction.Items.Add("LIKE");
                    }     
                    else if(CaptionAttribute.Instance.EnumTypes.Contains (fieldType .BaseType ))   //包含枚举
                    {
                        
                        TextBox_FilterValue.Visible = false;
                        DropDownList_FilterValue.Visible = true;
                        DropDownList_FilterValue.Items.Clear();
                       
                        object[] parameters =new object[1]{0};
                        TEnum fieldObject = fieldType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as TEnum;
                        //if (fieldObject != null)
                        {
                            BaseEnum baseEnum = fieldObject.BaseEnumType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as BaseEnum;
                            if (baseEnum != null)
                            {
                                foreach (EnumatorProperty enumProperty in baseEnum.BaseEnumProperty.EnumatorPropertyList)
                                {
                                    DropDownList_FilterValue.Items.Add(new ListItem(enumProperty.Label, enumProperty.EnumValue.ToString ()));
                                }    
                            }
                        }
                    }
                }
            }


            if (DropDownList_FilterValue.Items.Count > 0)
                DropDownList_FilterValue.SelectedIndex = 0;
            if (DropDownList_FilterAction.Items.Count > 0)
                DropDownList_FilterAction.SelectedIndex = 0;
        }
        #endregion

        #region 事件
        protected void Button_Cancel_Click(object sender, EventArgs e)
        {
            ClosePage();
        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {
            string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
            string queryXmlFileName = Path.Combine(queryXmlFilePath, Request["queryname"] + ".xml");
            DataSet dSet = new DataSet();
            dSet.ReadXml(queryXmlFileName);
            DataTable rangeDataTable = dSet.Tables[RuleQueryTable.RangeDataTableName ];
            if (rangeDataTable == null)
            {
                rangeDataTable = new DataTable();
                rangeDataTable.TableName =RuleQueryTable .RangeDataTableName ;
                rangeDataTable.Columns.Clear();
                rangeDataTable.Columns.Add("ID");
                rangeDataTable.Columns["ID"].AllowDBNull = false;
                rangeDataTable.Columns["ID"].DataType = typeof(int);
                rangeDataTable.Columns.Add("分组");
                rangeDataTable.Columns["分组"].AllowDBNull = false;
                rangeDataTable.Columns["分组"].DataType = typeof(int);
                rangeDataTable.Columns.Add("表名");
                rangeDataTable.Columns["表名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("字段名");
                rangeDataTable.Columns["字段名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("过滤操作");
                rangeDataTable.Columns["过滤操作"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置的值");
                rangeDataTable.Columns["设置的值"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置描述");
                rangeDataTable.Columns["设置描述"].AllowDBNull = false;
            }

            if (Request["type"] == "edit")
            {
                DataRow[] dRows = rangeDataTable.Select("ID='" + Request["refid"] + "'");
                if (dRows.Length > 0)
                {
                    dRows[0]["字段名"] = DropDownList_FieldName.SelectedValue;
                    dRows[0]["过滤操作"] = DropDownList_FilterAction.SelectedValue;
                    dRows[0]["设置的值"] = TextBox_FilterValue .Visible ? TextBox_FilterValue.Text :DropDownList_FilterValue .SelectedValue ;
                    dRows[0]["设置描述"] = TextBox_Desc .Text ;
                    rangeDataTable.AcceptChanges();
                }
            }
            else if (Request["type"] == "new")
            {
                DataTable sortDataTable = dSet.Tables[RuleQueryTable.SortingDataTableName ];
                int rangeID = rangeDataTable.Rows.Count + ((sortDataTable != null) ? sortDataTable.Rows.Count : 0);
                DataRow newRow = rangeDataTable.NewRow();
                newRow["ID"] = rangeID;
                newRow["分组"] = 0;
                newRow["表名"] = Request["tablename"];
                newRow["字段名"] = DropDownList_FieldName.SelectedValue;
                newRow["过滤操作"] = DropDownList_FilterAction.SelectedValue;
                newRow["设置的值"] = TextBox_FilterValue.Visible ? TextBox_FilterValue.Text : DropDownList_FilterValue.SelectedValue;
                newRow["设置描述"] = TextBox_Desc.Text;
                rangeDataTable.Rows.Add(newRow);
                rangeDataTable.AcceptChanges();
                if (dSet.Tables[RuleQueryTable.RangeDataTableName ] == null)
                    dSet.Tables.Add(rangeDataTable);
            }
            File.Delete(queryXmlFileName);
            dSet.WriteXml(queryXmlFileName);
            ClosePage();
        }


        private void ClosePage()
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseWindow", "<script type=\"text/javascript\">closeWindow();</script>", false);
        }
        #endregion

        protected void DropDownList_FieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitFieldType();                     
        }
    }
}
